package com.df.tv.launcher.view;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.df.tv.launcher.R;

import com.telecom.tv189.comlib.dynamicui.AttributeKey;
import com.telecom.tv189.comlib.dynamicui.DynamicView;
import com.telecom.tv189.comlib.util.Attributes;
import com.telecom.tv189.comlib.view.XUtilsImageView;

public class SwitchView extends RelativeLayout implements DynamicView {

    // xxhuang add
    // for auto gen
    public static final String CLASS_PATTERN = "SwitchView";

    public static final String ATTR_RESOURCE = "resource";
    // xxhuang end

    private ViewPager mViewPager;
    private TextView mMovieTitle;
    private TextView mMovieYear;
    private TextView mPosition;
    private PointsView mPoint;
    private List<ImageView> mImages = new ArrayList<ImageView>();
    private List<PlayItem> mResources = new ArrayList<PlayItem>();
    private int mPos = -1;

    private interface HandleAction {
        int SWICH = 1, REQUEST_FOCUSE = 2;
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
            case HandleAction.SWICH:
                mPos = msg.arg1;
                /*
                 * if(mResources != null
                 * && mResources.size()
                 * > 0 && mPos <
                 * mResources.size()){ }
                 */
                mViewPager.setCurrentItem(mPos);
                if (mResources != null && mResources.size() > 0) {
                    setImageByURL(mResources.get(mPos % mResources.size()).getImgsrc());
                    setPreviewTitle(mResources.get(mPos % mResources.size()).getName());
                    setPreviewYear(mResources.get(mPos % mResources.size()).getYear());
                    // setPosition(mPos%mResources.size()+1);
                    setPoint(mPos % mResources.size());
                }
                break;
            case HandleAction.REQUEST_FOCUSE:
                SwitchView.this.requestFocus();
                break;
            default:
                break;
            }

        };
    };

    public SwitchView(Context context) {
        super(context);
        init(context, 5);
    }

    public SwitchView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, 5);
    }

    private void init(Context context, int imageNum) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View mPreview = inflater.inflate(R.layout.switch_view, this);
        mViewPager = (ViewPager) mPreview.findViewById(R.id.vp_view);
        mMovieTitle = (TextView) mPreview.findViewById(R.id.tv_movie_title);
        mMovieYear = (TextView) mPreview.findViewById(R.id.tv_movie_year);
        mPosition = (TextView) mPreview.findViewById(R.id.tv_position);
        mPoint = (PointsView) mPreview.findViewById(R.id.pv_point);
        for (int i = 0; i < imageNum; i++) {
            XUtilsImageView imageView = new XUtilsImageView(context);
            imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            imageView.setImageResource(R.drawable.spec_default);
            imageView.setScaleType(ScaleType.FIT_XY);
            mImages.add(imageView);
        }
        mViewPager.setAdapter(new MyAdapter());
        mViewPager.setFocusable(false);
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Runnable() {
            public void run() {
                synchronized (this) {
                    if (mPos > Integer.MAX_VALUE) {
                        mPos = -1;
                    }
                    Message msg = mHandler.obtainMessage(HandleAction.SWICH);
                    msg.arg1 = ++mPos;
                    mHandler.sendMessage(msg);
                }
            }
        }, 5, 5, TimeUnit.SECONDS);
    }

    public void setPreviewTitle(String title) {
        if (mMovieTitle != null && !TextUtils.isEmpty(title)) {
            mMovieTitle.setText(title);
        }
    }

    public void setPreviewYear(String year) {
        if (mMovieYear != null && !TextUtils.isEmpty(year)) {
            mMovieYear.setText(year);
        }
    }

    class MyAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public int getItemPosition(Object object) {
            return super.getItemPosition(object);
        }

        @Override
        public void destroyItem(View arg0, int arg1, Object arg2) {
            ((ViewPager) arg0).removeView(mImages.get(arg1 % mImages.size()));
        }

        @Override
        public Object instantiateItem(View arg0, int arg1) {
            ((ViewPager) arg0).addView(mImages.get(arg1 % mImages.size()), 0);
            return mImages.get(arg1 % mImages.size());
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {

        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View arg0) {

        }

        @Override
        public void finishUpdate(View arg0) {

        }
    }

    /**
     * @param imgsrc
     */
    private void setImageByURL(String imgsrc) {
        if (mImages != null && mImages.size() > 0 && mPos >= 0 && !TextUtils.isEmpty(imgsrc)) {
            ((XUtilsImageView) (mImages.get(mPos % mImages.size()))).setImage(imgsrc);
        }
        else {
            ((XUtilsImageView) mImages.get(mPos % mImages.size())).setImageResource(R.drawable.spec_default);
        }
    }

    private void setImage(Bitmap bm) {
        if (mImages != null && mImages.size() > 0 && mPos >= 0 && bm != null) {
            mImages.get(mPos % mImages.size()).setImageBitmap(bm);
        }
        else {
            mImages.get(mPos % mImages.size()).setImageResource(R.drawable.spec_default);
        }
    }

    private void setPosition(int position) {
        if (mPosition != null) {
            if (position >= 0 && position < 10) {
                mPosition.setText(0 + String.valueOf(position));
            }
            else if (position > 9) {
                mPosition.setText(String.valueOf(position));
            }
        }
    }

    private void setPoint(int position) {
        if (mPoint != null) {
            mPoint.setPosition(position);
        }
    }

    public void setResource(List<PlayItem> resources) {
        this.mResources = resources;
    }

    public List<PlayItem> getResource() {
        return mResources;
    }

    public PlayItem getCurrentItem() {
        int size = mResources == null ? 0 : mResources.size();
        return mResources.get(mViewPager.getCurrentItem() % size);
    }

    public int getPosition() {
        int size = mResources == null ? 0 : mResources.size();
        return mViewPager.getCurrentItem() % size;
    }

    public List<ImageView> getmImages() {
        return mImages;
    }

    public void setmImages(List<ImageView> mImages) {
        this.mImages = mImages;
    }

    // call from dynamic ui layout inflater. init view status with attributes. add by xxhuang
    @Override
    public void applyAttributeSet(Attributes attrs, int defStyle) {
        setResource(attrs.get(ATTR_RESOURCE, List.class));
        setTag(mResources);
        setClickable(true);
        setFocusable(true);
        setFocusableInTouchMode(true);
        setBackgroundResource(R.drawable.preview_1_background);
        setDrawingCacheEnabled(true);

        if (attrs.getBoolean(AttributeKey.FOCUS, false) && this.isFocusable()) {
            mHandler.sendEmptyMessageDelayed(HandleAction.REQUEST_FOCUSE, 500);
        }

        //setPadding(0, 0, 0, 0);
    }

    public static class PlayItem implements Parcelable {
        public static final int PLAY_TYPE_NORMAL = 1; // 点播
        public static final int PLAY_TYPE_LIVE = 3; // 直播

        public static final int PLAY_TYPE_GAME = 2; // 游戏
        public static final int QUALITY_LOW = 0; // 普通
        public static final int QUALITY_MEDIUM = 1; // 高清
        public static final int QUALITY_HIGH = 2; // 超高清
        public static final String QUALITY_450P = "450P"; // 普通
        public static final String QUALITY_720P = "720P"; // 高清
        public static final String QUALITY_1080P = "1080P"; // 超高清
        public static final String QUALITY_DEFAULT = "default"; // 默认清晰度

        public static final String QUALITY_RTMP_LOW = "32"; // 普通
        public static final String QUALITY_RTMP_MEDIUM = "64"; // 高清
        public static final String QUALITY_RTMP_HIGH = "128"; // 超高清
        public static final int LOCAL = 1;
        public static final int NET = 0;
        /**
         * 独家首播
         */
        public static final int SORT_EXCLUSIVE_PREMIERE = 1;
        /**
         * 即将上架
         */
        public static final int SORT_RELEASED_SOON = 2;
        private String contentId; // 视频id
        private String title; // 视频名称
        private String videosrc; // 视频播放地址
        private String imgbasic; // 视频列表和详情页图片地址
        private String imgbig; // 首页图片地址
        private boolean isLoadedImg; // 视频图片是否已加载完毕
        private int pType = PLAY_TYPE_NORMAL; // 视频类型
        private int imageResourceId; // 视频默认图片
        private int local; // 是否本地视频
        private int quality = -1; // 视频清晰度
        private int playedTime; // 视频上次播放时间
        private String packageName; // 游戏包名（只供游戏用）
        private String programName; // 视频正在播放节目名（只供直播用）
        private String channelNo; // 视频频道号（只供直播用）
        private String cast; // 视频演员（只供点播用）
        private String director; // 视频导演（只供点播用）
        private String duration; // 视频长度（只供点播用）
        private String description; // 视频描述（只供点播用）
        private String year; // 年份
        private int sort; // 类别
        private String subcategoryName; // 电影类型
        private String state = "00"; // 该项状态 00:未删除未选中；01：删除状态未选中；10：删除状态选中；11未删除选中。
        private float averageScoreValue;
        private String orgairdate;
        private String originalcountry;
        private List<VideoUrl> videos;
        private int action = -1;
        private int length;

        public PlayItem() {

        }

        public int getLength() {
            return length;
        }

        public void setLength(int length) {
            this.length = length;
        }

        public int getAction() {
            return action;
        }

        public void setAction(int action) {
            this.action = action;
        }

        public List<VideoUrl> getVideos() {
            return videos;
        }

        public void setVideos(List<VideoUrl> videos) {
            this.videos = videos;
        }

        public String getRegion() {
            return originalcountry;
        }

        public void setRegion(String region) {
            this.originalcountry = region;
        }

        public String getDate() {
            return orgairdate;
        }

        public void setDate(String date) {
            this.orgairdate = date;
        }

        public String getCategory() {
            return subcategoryName;
        }

        public void setCategory(String category) {
            this.subcategoryName = category;
        }

        public float getScore() {
            return averageScoreValue;
        }

        public void setScore(float score) {
            this.averageScoreValue = score;
        }

        public int getSort() {
            return sort;
        }

        public void setSort(int sort) {
            this.sort = sort;
        }

        public String getYear() {
            if (year == null && orgairdate != null && orgairdate.length() > 3) {
                year = orgairdate.substring(0, 4);
            }
            return year;
        }

        public void setYear(String year) {
            this.year = year;
        }

        public String getActor() {
            return cast;
        }

        public void setActor(String actor) {
            this.cast = actor;
        }

        public String getDirector() {
            return director;
        }

        public void setDirector(String director) {
            this.director = director;
        }

        public String getDuration() {
            return duration;
        }

        public void setDuration(String duration) {
            this.duration = duration;
        }

        public String getChannelNo() {
            return channelNo;
        }

        public void setChannelNo(String channelNo) {
            this.channelNo = channelNo;
        }

        public String getProgramName() {
            return programName;
        }

        public void setProgramName(String programName) {
            this.programName = programName;
        }

        public String getPackageName() {
            return packageName;
        }

        public void setPackageName(String packageName) {
            this.packageName = packageName;
        }

        public int getQuality() {
            return quality;
        }

        public void setQuality(int quality) {
            this.quality = quality;
        }

        public String getDesc() {
            return description;
        }

        public void setDesc(String desc) {
            this.description = desc;
        }

        public int getpType() {
            return pType;
        }

        public void setpType(int pType) {
            this.pType = pType;
        }

        public int getImageResourceId() {
            return imageResourceId;
        }

        public void setImageResourceId(int imageResourceId) {
            this.imageResourceId = imageResourceId;
        }

        public String getId() {
            return contentId;
        }

        public void setId(String id) {
            this.contentId = id;
        }

        public String getName() {
            return title;
        }

        public int getPlayedTime() {
            return playedTime;
        }

        public void setPlayedTime(int playedTime) {
            this.playedTime = playedTime;
        }

        public void setName(String name) {
            this.title = name;
        }

        public String getVideosrc() {
            return videosrc;
        }

        public void setVideosrc(String videosrc) {
            this.videosrc = videosrc;
        }

        public String getImgsrc() {
            if (TextUtils.isEmpty(imgbasic)) { return imgbig; }
            return imgbasic;
        }

        public void setImgsrc(String imgsrc) {
            this.imgbasic = imgsrc;
        }

        @Override
        public int describeContents() {
            return 0;
        }

        public boolean isLoadedImg() {
            return isLoadedImg;
        }

        public void setLoadedImg(boolean isLoadedImg) {
            this.isLoadedImg = isLoadedImg;
        }

        public int getLocal() {
            return local;
        }

        public void setLocal(int local) {
            this.local = local;
        }

        public String getState() {
            return state;
        }

        public void setState(String state) {
            this.state = state;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(contentId);
            dest.writeString(title);
            dest.writeString(videosrc);
            dest.writeString(imgbasic);
            dest.writeInt(pType);
            dest.writeInt(local);
            dest.writeInt(playedTime);
            dest.writeInt(quality);
            dest.writeString(channelNo);
            dest.writeString(state);
        }

        public static final Parcelable.Creator<PlayItem> CREATOR = new Creator<PlayItem>() {

            @Override
            public PlayItem[] newArray(int size) {
                return new PlayItem[size];
            }

            @Override
            public PlayItem createFromParcel(Parcel source) {
                PlayItem playItem = new PlayItem();
                playItem.contentId = source.readString();
                playItem.title = source.readString();
                playItem.videosrc = source.readString();
                playItem.imgbasic = source.readString();
                playItem.pType = source.readInt();
                playItem.local = source.readInt();
                playItem.playedTime = source.readInt();
                playItem.quality = source.readInt();
                playItem.channelNo = source.readString();
                playItem.state = source.readString();
                return playItem;
            }
        };

        public String getQualityStr() {
            String result = "";
            switch (pType) {
            case PLAY_TYPE_NORMAL:
                switch (quality) {
                case PlayItem.QUALITY_LOW:
                    result = QUALITY_450P;
                    break;
                case PlayItem.QUALITY_MEDIUM:
                    result = QUALITY_720P;
                    break;
                case PlayItem.QUALITY_HIGH:
                    result = QUALITY_1080P;

                    break;

                default:
                    break;
                }
                break;
            case PLAY_TYPE_LIVE:
                switch (quality) {
                case PlayItem.QUALITY_LOW:
                    result = QUALITY_RTMP_LOW;
                    break;
                case PlayItem.QUALITY_MEDIUM:
                    result = QUALITY_RTMP_MEDIUM;
                    break;
                case PlayItem.QUALITY_HIGH:
                    result = QUALITY_RTMP_HIGH;
                    break;

                default:
                    break;
                }
                break;

            default:
                break;
            }

            return result;
        }
    }

    public static class VideoUrl {
        private String quality;
        private String playUrl;

        public String getQuality() {
            return quality;
        }

        public void setQuality(String quality) {
            this.quality = quality;
        }

        public String getPlayUrl() {
            return playUrl;
        }

        public void setPlayUrl(String playUrl) {
            this.playUrl = playUrl;
        }

    }
}
